package com.asktgapp.user.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.asktgapp.JGTool.Utils;
import com.asktgapp.R;
import com.asktgapp.application.ApiUtil;
import com.asktgapp.application.Apiservice;
import com.asktgapp.architecture.retrofit.ApiException;
import com.asktgapp.architecture.retrofit.ApiResponseBody;
import com.asktgapp.architecture.rxjava.ExceptionHandle;
import com.asktgapp.base.BaseFragment;
import com.asktgapp.base.SearchBaseActivity;
import com.asktgapp.engineer.activity.AnswerQuestionActivity;
import com.asktgapp.model.HomeServiceVO;
import com.asktgapp.model.SearchVO;
import com.asktgapp.modulebase.common.adapter.BaseAdapter;
import com.asktgapp.modulebase.common.adapter.BaseViewHolder;
import com.asktgapp.modulebase.common.util.PreferencesUtil;
import com.asktgapp.modulebase.common.util.Util;
import com.asktgapp.user.activity.AskDetialActivity;
import com.asktgapp.user.activity.EngineerDetailActivity;
import com.asktgapp.user.activity.FreeAskAnswerDetailActivity;
import com.asktgapp.user.activity.HomeServiceDetailActivity;
import com.asktgapp.user.activity.IndustryInfoDetailActivity;
import com.asktgapp.user.activity.QiuZuDetailActivity;
import com.asktgapp.user.activity.RentDetailActivity;
import com.asktgapp.user.activity.SearchMoreActivity;
import com.asktgapp.user.activity.UsedMachineDetailActivity;
import com.asktgapp.utils.ImageDisplayUtil;
import com.asktgapp.widget.RefreshRecyclerView;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * time:2018/1/23
 * Create By ZhaoKai
 * Email: dczk@foxmail.com
 * <p>
 * Description: 改为在activity中进行逻辑，弃用
 */

public class SearcResultFragment extends BaseFragment {
    private RefreshRecyclerView mRefreshRecyclerView;
    private RecyclerView mRecylerView;
    private BaseAdapter mBaseAdapter;
    private int mPage = 1;
    private String key;
    private int type;
    private SearchVO mSearchVO;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        ViewGroup viewGroup = (ViewGroup) inflater.inflate(R.layout.fragment_search_result, container, false);
        return super.onCreateView(inflater, viewGroup, savedInstanceState);
    }

    @Override
    protected void initView(View rootView) {
        getBaseActivity().setBackNavigationIcon();
        key = getActivity().getIntent().getStringExtra("key");
        type = getActivity().getIntent().getIntExtra("type", 0);
        mRefreshRecyclerView = rootView.findViewById(R.id.recycle);
        mRecylerView = mRefreshRecyclerView.getRecyclerView();
        mRefreshRecyclerView.setLoadMoreAction(new RefreshRecyclerView.Action() {
            @Override
            public void onAction(int page) {
                mPage = page;
                getNetData(mPage);
            }
        });
        mRefreshRecyclerView.setRefreshAction(new RefreshRecyclerView.Action() {
            @Override
            public void onAction(int page) {
                mPage = page;
                getNetData(mPage);
            }
        });
        mRecylerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
        mBaseAdapter = new BaseAdapter(getActivity()) {
            @Override
            public BaseViewHolder getViewHolder(ViewGroup parent, int viewType) {
                BaseViewHolder holder = null;
                if (viewType == 0) {//工程师
                    holder = new BaseViewHolder(LayoutInflater.from(getActivity()).inflate(R.layout.item_search_projecter, parent, false),
                            new BaseViewHolder.Callbacks() {
                                @Override
                                public void bind(BaseViewHolder holder, Object data) {
                                    RelativeLayout head = holder.getView(R.id.rl_head);
                                    TextView more = holder.getView(R.id.tv_home_more_question);
                                    if (data instanceof SearchVO.ProjecterListBean) {
                                        SearchVO.ProjecterListBean bean = (SearchVO.ProjecterListBean) data;
                                        head.setVisibility(View.GONE);
                                        ImageView headImg = holder.getView(R.id.iv_head_engineer);
                                        TextView mTag1 = holder.getView(R.id.tv_tag1);
                                        TextView mTag2 = holder.getView(R.id.tv_tag2);
                                        ImageDisplayUtil.loadCircleHeadImage(getActivity(), headImg, bean.getUserPic());
                                        holder.setText(R.id.tv_reason, bean.getRecommendReason());
                                        holder.setText(R.id.tv_price, "¥ " + bean.getAdvisoryPrice() + "元起");
                                        holder.setText(R.id.tv_name, bean.getRealname());
                                        if (Util.isEmpty(bean.getLabel())) {
                                            mTag1.setVisibility(View.GONE);
                                            mTag2.setVisibility(View.GONE);
                                        } else {
                                            String[] str = bean.getLabel().split(",");
                                            if (str.length == 0) {
                                                mTag1.setVisibility(View.GONE);
                                                mTag2.setVisibility(View.GONE);
                                            } else if (str.length == 1) {
                                                if (Util.isEmpty(str[0])) {
                                                    mTag1.setVisibility(View.GONE);
                                                } else {
                                                    mTag1.setVisibility(View.VISIBLE);
                                                }
                                                mTag2.setVisibility(View.GONE);
                                                mTag1.setText(str[0]);
                                            } else if (str.length >= 2) {
                                                mTag1.setVisibility(View.VISIBLE);
                                                mTag2.setVisibility(View.VISIBLE);
                                                mTag1.setText(str[0]);
                                                mTag2.setText(str[1]);
                                            }
                                        }
                                    }
                                }

                                @Override
                                public void onItemClick(View view, int position) {
                                    SearchVO.ProjecterListBean bean = (SearchVO.ProjecterListBean) mBaseAdapter.getData().get(position);
                                    Intent intent = new Intent(getActivity(), EngineerDetailActivity.class);
                                    intent.putExtra("id", String.valueOf(bean.getId()));
                                    startActivity(intent);
                                }
                            });
                } else if (viewType == 1) {//问答
                    holder = new BaseViewHolder(LayoutInflater.from(getActivity()).inflate(R.layout.item_search_ask, parent, false),
                            new BaseViewHolder.Callbacks() {
                                @Override
                                public void bind(BaseViewHolder holder, Object data) {
                                    RelativeLayout head = holder.getView(R.id.rl_head);
                                    TextView more = holder.getView(R.id.tv_home_more_question);
                                    RelativeLayout answer1 = holder.getView(R.id.rl_answer);
                                    TextView defaultText = holder.getView(R.id.tv_default);
                                    if (data instanceof SearchVO.ProblemListBean) {
                                        SearchVO.ProblemListBean bean = (SearchVO.ProblemListBean) data;
                                        head.setVisibility(View.GONE);
                                        ImageView Qhead = holder.getView(R.id.iv_head_ask);
                                        TextView name = holder.getView(R.id.tv_ask_name);
                                        TextView time = holder.getView(R.id.tv_ask_time);
                                        TextView question = holder.getView(R.id.tv_question);
                                        TextView answer = holder.getView(R.id.tv_answer);
                                        ImageView Ahead = holder.getView(R.id.iv_answer_head);
                                        TextView answerName = holder.getView(R.id.tv_answer_name);
                                        TextView zan = holder.getView(R.id.tv_zan);
                                        TextView label1 = holder.getView(R.id.tv_answer_label1);
                                        TextView label2 = holder.getView(R.id.tv_answer_label2);
                                        //提问人头像
                                        ImageDisplayUtil.loadCircleHeadImage(getActivity(), Qhead, bean.getQUserPic());
                                        //提问人昵称
                                        name.setText(bean.getQUersName());
                                        Date date = Util.StrToDate(bean.getAddTime(), "yyyy.MM.dd HH:mm:ss");
                                        String timeStr = Utils.getAskTime(date);
//                                        if (data != null)
//                                            timeStr = Util.DateToStr(date, "yyyy-MM-dd");
                                        time.setText(timeStr);
                                        question.setText(bean.getQContent());
                                        if (bean.getIsAnswer() == 1) {//已解答
                                            answer1.setVisibility(View.VISIBLE);
                                            defaultText.setVisibility(View.GONE);
                                            ImageDisplayUtil.loadCircleHeadImage(getActivity(), Ahead, bean.getAUserPic());
                                            answerName.setText(bean.getaRealName());
                                            answer.setText(bean.getAContent());
                                            zan.setText(String.valueOf(bean.getLikeNumber()));
                                            String[] lable = bean.getALabel().split(",");
                                            switch (lable.length) {
                                                case 0:
                                                    label1.setVisibility(View.GONE);
                                                    label2.setVisibility(View.GONE);
                                                    break;
                                                case 1:
                                                    if (Util.isEmpty(lable[0])) {
                                                        label1.setVisibility(View.GONE);
                                                    } else {
                                                        label1.setVisibility(View.VISIBLE);
                                                    }
                                                    label1.setText(lable[0]);
                                                    label2.setVisibility(View.GONE);
                                                    break;
                                                case 2:
                                                    label1.setVisibility(View.VISIBLE);
                                                    label1.setText(lable[0]);
                                                    label2.setVisibility(View.VISIBLE);
                                                    label2.setText(lable[1]);
                                                    break;
                                                default:
                                                    label1.setVisibility(View.VISIBLE);
                                                    label1.setText(lable[0]);
                                                    label2.setVisibility(View.VISIBLE);
                                                    label2.setText(lable[1]);
                                                    break;
                                            }

                                        } else {
                                            //未解答
                                            answer1.setVisibility(View.GONE);
//                                            defaultText.setVisibility(View.VISIBLE);
                                        }
                                    }
                                }

                                @Override
                                public void onItemClick(View view, int position) {
                                    SearchVO.ProblemListBean bean = (SearchVO.ProblemListBean) mBaseAdapter.getData().get(position);
                                    FreeAskAnswerDetailActivity.startFreeAskAnswerDetailActivty(String.valueOf( bean.getQId()),getContext());
                                }
                            });

                } else if (viewType == 2) {//二手机
                    holder = new BaseViewHolder(LayoutInflater.from(getActivity()).inflate(R.layout.item_search_towhard, parent, false),
                            new BaseViewHolder.Callbacks() {
                                @Override
                                public void bind(BaseViewHolder holder, Object data) {
                                    RelativeLayout head = holder.getView(R.id.rl_head);
                                    TextView more = holder.getView(R.id.tv_home_more_question);
                                    if (data instanceof SearchVO.TwoHardListBean) {
                                        SearchVO.TwoHardListBean bean = (SearchVO.TwoHardListBean) data;
                                        head.setVisibility(View.GONE);
                                        ImageView saleState = holder.getView(R.id.iv_saled);
                                        ImageView img = holder.getView(R.id.iv_machine);
                                        ImageDisplayUtil.LoadNetImageWithUrl(img, getActivity(), bean.getBanner_pic());
                                        holder.setText(R.id.tv_used_machine_name, bean.getTitle());
                                        holder.setText(R.id.detail, Utils.getDateYear(bean.getProduction_date()) +
                                                " | " + Utils.D2I(bean.getWorking_hours()) + "小时 | " + bean.getPro_name().replaceAll("省", "") + " " + bean.getCity_name().replaceAll("市", ""));
                                        DecimalFormat df = new DecimalFormat("0.00");
                                        holder.setText(R.id.tv_price, df.format(bean.getPrice()) + bean.getPrice_unit() + "");
                                        if (bean.getState() == 0) {
                                            saleState.setVisibility(View.GONE);
                                        } else {
                                            saleState.setVisibility(View.VISIBLE);
                                        }
                                    }
                                }

                                @Override
                                public void onItemClick(View view, int position) {
                                    SearchVO.TwoHardListBean bean = (SearchVO.TwoHardListBean) mBaseAdapter.getData().get(position);
                                    Intent intent = new Intent(getActivity(), UsedMachineDetailActivity.class);
                                    intent.putExtra("id", String.valueOf(bean.getId()));
                                    intent.putExtra("unit", bean.getPrice_unit());
                                    startActivity(intent);
                                }
                            });

                } else if (viewType == 3) {//租赁
                    holder = new BaseViewHolder(LayoutInflater.from(getActivity()).inflate(R.layout.item_search_lease, parent, false),
                            new BaseViewHolder.Callbacks() {
                                @Override
                                public void bind(BaseViewHolder holder, Object data) {
                                    RelativeLayout head = holder.getView(R.id.rl_head);
                                    TextView more = holder.getView(R.id.tv_home_more_question);
                                    if (data instanceof SearchVO.LeaseListBean) {
                                        SearchVO.LeaseListBean bean = (SearchVO.LeaseListBean) data;
                                        head.setVisibility(View.GONE);
                                        ImageView state = holder.getView(R.id.iv_state);
                                        ImageView img = holder.getView(R.id.iv_machine);
                                        holder.setText(R.id.tv_used_machine_name, bean.getTitle());
                                        holder.setText(R.id.tv_price, Utils.D2I(bean.getPrice()) + bean.getPrice_unit() + "");
                                        String pro = bean.getPro_name().replaceAll("省", "");
                                        String city = bean.getCity_name().replaceAll("市", "");
                                        ImageDisplayUtil.LoadNetImageWithUrl(img, getActivity(), bean.getBanner_pic());
//                                        if (pro.equals(city)) {
//                                            holder.setText(R.id.tv_detail, Utils.getDateAll(bean.getAdd_time())
//                                                    + " | " + pro);
//
//                                        } else {
                                        holder.setText(R.id.tv_detail, Utils.getDateYMD(bean.getAdd_time())
                                                + " | " + pro + " " + city);
//                                        }
                                        //出租0:待售 1:已售 求租没有
                                        state.setVisibility(View.VISIBLE);
                                        if (bean.getState() == 0) {
                                            state.setImageResource(R.mipmap.bg_rent);
                                        } else {
                                            state.setImageResource(R.mipmap.bg_busy);
                                        }
                                    }
                                }

                                @Override
                                public void onItemClick(View view, int position) {
                                    SearchVO.LeaseListBean bean = (SearchVO.LeaseListBean) mBaseAdapter.getData().get(position);
                                    Intent intent = new Intent(getActivity(), RentDetailActivity.class);
                                    intent.putExtra("id", String.valueOf(bean.getId()));
                                    intent.putExtra("unit", bean.getPrice_unit());
                                    startActivity(intent);
                                }
                            });

                } else if (viewType == 4) {//咨讯
                    holder = new BaseViewHolder(LayoutInflater.from(getActivity()).inflate(R.layout.item_search_info, parent, false),
                            new BaseViewHolder.Callbacks() {
                                @Override
                                public void bind(BaseViewHolder holder, Object data) {
                                    RelativeLayout head = holder.getView(R.id.rl_head);
                                    TextView more = holder.getView(R.id.tv_home_more_question);
                                    ImageView img = holder.getView(R.id.iv_industry_img);
                                    TextView title = holder.getView(R.id.tv_industry_title);
                                    TextView time = holder.getView(R.id.tv_industry_time);
                                    TextView comment = holder.getView(R.id.tv_industry_read_number);
                                    TextView like = holder.getView(R.id.tv_industry_like);
                                    if (data instanceof SearchVO.InfoListBean) {
                                        SearchVO.InfoListBean bean = (SearchVO.InfoListBean) data;
                                        head.setVisibility(View.GONE);
                                        ImageDisplayUtil.LoadNetImage(img, getActivity(), bean.getBannerPic());
                                        title.setText(bean.getTitle());
                                        time.setText(Utils.getDateYMD(bean.getAddTime()));
                                        comment.setText(String.valueOf(bean.getCommentNumber()));
                                        like.setText(String.valueOf(bean.getLikeNumber()));
                                    }
                                }

                                @Override
                                public void onItemClick(View view, int position) {
                                    SearchVO.InfoListBean bean = (SearchVO.InfoListBean) mBaseAdapter.getData().get(position);
                                    Intent intent = new Intent(getActivity(), IndustryInfoDetailActivity.class);
                                    intent.putExtra("id", String.valueOf(bean.getId()));
                                    startActivity(intent);
                                }
                            });

                } else if (viewType == 5) {
                    holder = new BaseViewHolder(LayoutInflater.from(getActivity()).inflate(R.layout.item_search_qiuzu, parent, false), new BaseViewHolder.Callbacks() {
                        @Override
                        public void bind(BaseViewHolder holder, Object data) {
                            RelativeLayout head = holder.getView(R.id.rl_head);
                            TextView more = holder.getView(R.id.tv_home_more_question);
                            if (data instanceof SearchVO.QiuZuListBean) {
                                SearchVO.QiuZuListBean bean = (SearchVO.QiuZuListBean) data;
                                head.setVisibility(View.GONE);
                                holder.setText(R.id.tv_qiuzu_title, bean.getTitle());
                                holder.setText(R.id.tv_price, Utils.D2I(bean.getPrice()) + bean.getPrice_unit() + "");
                                String pro = bean.getPro_name().replaceAll("省", "").replace("市", "");
                                String city = bean.getCity_name().replaceAll("市", "");
//                                if (pro.equals(city)) {
//                                    holder.setText(R.id.tv_info, Utils.getDateAll(bean.getAdd_time())
//                                            + " | " + pro + " | "
//                                            + "工期" + bean.getTime_limit() + "天");
//                                } else
                                holder.setText(R.id.tv_info, Utils.getDateYMD(bean.getAdd_time())
                                        + " | " + pro + " "
                                        + city + " | "
                                        + "工期" + bean.getTime_limit() + "天");
                            }


                        }

                        @Override
                        public void onItemClick(View view, int position) {
                            SearchVO.QiuZuListBean bean = (SearchVO.QiuZuListBean) mBaseAdapter.getData().get(position);
                            Intent intent = new Intent(getActivity(), QiuZuDetailActivity.class);
                            intent.putExtra("id", String.valueOf(bean.getId()));
                            startActivity(intent);
                        }
                    });
                }else if(viewType==6){
                    holder = new BaseViewHolder(LayoutInflater.from(getActivity()).inflate(R.layout.item_home_service, parent, false),
                            new BaseViewHolder.Callbacks() {
                                @Override
                                public void bind(BaseViewHolder holder, Object data) {
                                    if (data instanceof SearchVO.ServiceListBean) {
                                        ImageView userHead = holder.getView(R.id.userHead);
                                        SearchVO.ServiceListBean bean = (SearchVO.ServiceListBean) data;

                                        if (mBaseAdapter.getItemIndex(bean) == 0)
                                            holder.getView(R.id.tvLine).setVisibility(View.VISIBLE);
                                        else
                                            holder.getView(R.id.tvLine).setVisibility(View.GONE);
                                        userHead.setVisibility(View.VISIBLE);
                                        holder.getView(R.id.userName).setVisibility(View.VISIBLE);
                                        holder.getView(R.id.serviceType).setVisibility(View.GONE);
                                        holder.setText(R.id.userName, bean.getUserName());
                                        holder.setText(R.id.serviceContent, bean.getInfo());
                                        Date date = Util.StrToDate(bean.getAddTime(), "yyyy.MM.dd HH:mm:ss");
                                        String timeStr = Utils.getAskTime(date);
                                        holder.setText(R.id.addTime, timeStr);
                                        String pro = bean.getProviceName().replaceAll("省", "");
                                        String city = bean.getCityName().replaceAll("市", "");
                                        if (TextUtils.isEmpty(pro + " " + city))
                                            holder.setText(R.id.serviceAddress, "未知地区");
                                        else
                                            holder.setText(R.id.serviceAddress, pro + " " + city);


                                            holder.getView(R.id.serviceStatus).setVisibility(View.GONE);

//                                    ImageDisplayUtil.LoadNetImageWithUrl(userHead, getActivity(), bean.getUserPic());
                                        ImageDisplayUtil.loadCircleHeadImage(getActivity(), userHead, bean.getUserPic());
                                        String type = bean.getType();
                                        String serviceType = "维修";
                                        if (type.equals("1")) {
                                            serviceType = ("维修");
                                        } else if (type.equals("2")) {
                                            serviceType = ("检车");
                                        } else if (type.equals("3")) {
                                            serviceType = ("保养");
                                        } else if (type.equals("4")) {
                                            serviceType = ("评估");
                                        }
                                        holder.getView(R.id.serviceTypeTop).setVisibility(View.VISIBLE);
                                        holder.setText(R.id.serviceTypeTop, serviceType);

                                    }
                                }

                                @Override
                                public void onItemClick(View view, int position) {
                                    if (checkIsLogin("登录后可体验更多内容")) {
                                        SearchVO.ServiceListBean bean = (SearchVO.ServiceListBean) mBaseAdapter.getData().get(position);
                                        Intent intent = new Intent(getActivity(), HomeServiceDetailActivity.class);
                                        intent.putExtra("id", String.valueOf(bean.getId()));
//                                intent.putExtra("unit", bean.getPrice_unit());
                                        startActivity(intent);
                                    }
                                }
                            });
                }
                return holder;
            }

            @Override
            public int getItemViewType(int position) {
                Object bean = mBaseAdapter.getData().get(position);
                if (bean instanceof SearchVO.ProjecterListBean) {
                    return 0;
                }
                if (bean instanceof SearchVO.ProblemListBean)
                    return 1;
                if (bean instanceof SearchVO.TwoHardListBean)
                    return 2;
                if (bean instanceof SearchVO.LeaseListBean)
                    return 3;
                if (bean instanceof SearchVO.InfoListBean)
                    return 4;
                if (bean instanceof SearchVO.QiuZuListBean)
                    return 5;
                if (bean instanceof SearchVO.ServiceListBean)
                    return 6;
                return 0;
            }

        };
        mRecylerView.setAdapter(mBaseAdapter);
    }

    @Override
    public void loadData() {
        visibleLoading();
        getNetData(mPage);

    }

    private void getNetData(final int mPage) {
        Apiservice apiservice = ApiUtil.getInstance().create();
        HashMap params = new HashMap();
        params.put("keyWord", key);
        params.put("type", type);
        params.put("page", mPage);
        Call<ApiResponseBody<SearchVO>> call = apiservice.findMoreList(params);
        call.enqueue(new Callback<ApiResponseBody<SearchVO>>() {
            @Override
            public void onResponse(Call<ApiResponseBody<SearchVO>> call, Response<ApiResponseBody<SearchVO>> response) {
                mRefreshRecyclerView.endPage();
                inVisibleLoading();
                if (response.isSuccessful()) {
                    mSearchVO = response.body().getResult();
                    List list = new ArrayList();
                    if (type == 0) {
                        list = mSearchVO.getProjecterList();
                    } else if (type == 1) {
                        list = mSearchVO.getProblemList();
                    } else if (type == 2) {
                        list = mSearchVO.getTwoHardList();
                    } else if (type == 3) {
                        list = mSearchVO.getLeaseList();
                    } else if (type == 4) {
                        list = mSearchVO.getQiuZuList();
                    } else if (type == 5) {
                        list = mSearchVO.getInfoList();
                    }else if(type ==6){
                        list = mSearchVO.getServiceList();
                    }
                    if (mPage == 1) {
                        if (list.size() == 0) {
                            visibleLoading();
                        } else {
                            mBaseAdapter.setData(list);
                            mRefreshRecyclerView.showNextMore(mPage);
                        }
                    } else {
                        if (list.size() == 0) {
                            mRefreshRecyclerView.showNoMore();
                        } else {
                            mBaseAdapter.addData(BaseAdapter.AddType.LASE, list);
                            mRefreshRecyclerView.showNextMore(mPage);
                        }
                    }

                } else {
                    showTost(response.raw().message(), 0);
                }
            }

            @Override
            public void onFailure(Call<ApiResponseBody<SearchVO>> call, Throwable t) {
                mRefreshRecyclerView.endPage();
                inVisibleLoading();
                ApiException apiException = ExceptionHandle.handleException(t);
                if (apiException.isTokenInvalid()) {
                    showUnLoginSnackbar();
                } else if (apiException.isNetConnected()) {
                    showSetNetworkSnackbar();
                } else {
                    showTost(apiException.getMessage(), 0);
                }
            }
        });

    }
}
